package process_demo.data_share;

/**
 * @author haomin
 * @date 2022/04/20 21:44
 **/
// 想办法让子线程和主线程的引用指向同一个对象即可
public class Main5 {
    static class SomeObject {
        int r = 0;
    }

    static class MyThread extends Thread {
        private final SomeObject someObject;

        public MyThread(SomeObject someObject) {
            this.someObject = someObject;   // 指向 主线程.main.someObject 指向的对象
        }

        @Override
        public void run() {
            for (int i = 0; i < 1000; i++) {
                someObject.r++;         // 指向 主线程.main.someObject 指向的对象
            }
            System.out.println(getName() + ":" + someObject.r);     // 1000
        }
    }

    public static void main(String[] args) throws InterruptedException {
        SomeObject someObject = new SomeObject();   // 创建对象

        MyThread t = new MyThread(someObject);      // 把 SomeObject 的引用传入
        t.start();

        t.join();
        System.out.println(Thread.currentThread().getName() + ":" + someObject.r);  // 1000
    }
}